package com.hulman.oms.web;

import com.hulman.oms.bean.MsgSummary;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.Msg;
import com.hulman.oms.bean.User;
import com.hulman.oms.service.MsgService;
import com.hulman.oms.util.NumberUtil;
import com.hulman.oms.util.SubjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@RestController
public class MsgController
{
    @Autowired
    private MsgService msgService;

    @GetMapping("/msgs/{id}")
    public Result findMsgById(@PathVariable Integer id)
    {
        Msg msg = msgService.findMsgById(id);
        return new Result(msg);
    }

    @GetMapping("/msgs")
    public Result findMsgs(Integer page, Integer limit, String type, Integer ownerId, String ownerName, String content)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        map.put("type", type);
        map.put("ownerId", ownerId);
        map.put("ownerName", ownerName);
        map.put("content", content);
        return msgService.findMsgsResult(map);
    }

    @GetMapping("/msgs/summary")
    public Result findMsgSummary()
    {
        User user = SubjectUtil.getUser();
        Integer ownerId = user.getId();
        List<MsgSummary> list = new ArrayList<>();
        list.add(msgService.findMsgSummary(ownerId, "om"));
        /*list.add(msgService.findMsgSummary(ownerId, "repair"));
        list.add(msgService.findMsgSummary(ownerId, "plan"));*/
        list.add(msgService.findMsgSummary(ownerId, "sys"));
        return new Result(list, list.size());
    }

    /**
     * 最新消息
     *
     * @param ownerId 消息所有人
     * @param msgId   最近消息ID
     * @return
     */
    @PostMapping("/msgs/latest")
    public Result findLatestMsgs(Integer ownerId, Integer msgId)
    {
        List<Msg> msg = msgService.findLatestMsgs(ownerId, msgId);
        return new Result(msg, msg.size());
    }

    @PostMapping("/msgs/read")
    public Result readMsg(Integer id)
    {
        msgService.readMsg(id);
        return Result.SUCCESS;
    }

    @PostMapping("/msgs/read-all")
    public Result readAllMsgs(String type)
    {
        User user = SubjectUtil.getUser();
        msgService.readAllMsgs(user.getId(), type);
        return Result.SUCCESS;
    }

    @PostMapping("/msgs/clear-all")
    public Result clearAllMsgs(String type)
    {
        User user = SubjectUtil.getUser();
        msgService.clearAllMsgs(user.getId(), type);
        return Result.SUCCESS;
    }

    @DeleteMapping("/msgs/{ids}")
    public Result deleteMsgById(@PathVariable String ids)
    {
        int[] idArrays = NumberUtil.parseIntArray(ids);
        for (Integer id : idArrays)
        {
            msgService.deleteMsgById(id);
        }
        return Result.SUCCESS;
    }

}
